﻿/* Sharepoint Developer's Hub 
 * Author       : Ram Prasad Meenavalli (ram@spdeveloper.co.in)
 * Date         : Jun 30 2012
 * Description  : This class represents is used for creating the timer job, which will install and activate the newly installed features in the
 * updated solution.
 */
using System;
using Microsoft.SharePoint.Administration;
using SPDev.Powershell;

namespace SPDev.Administration
{
    internal class SPFeatureInstallationJobDefinition : SPJobDefinition
    {
        [Persisted]
        private String features;
        [Persisted]
        private bool Force;
        [Persisted]
        private String solutionId;
        public SPFeatureInstallationJobDefinition() { }
        public SPFeatureInstallationJobDefinition(string solutionName, Guid solutionId, int LCID, SPTimerService service, String newFeatures, bool Force)
            : base(SPFeatureInstallationJobDefinition.GenerateJobName(solutionName, solutionId, LCID), service, null, SPJobLockType.None)
		{
            this.features = newFeatures;
            this.Force = Force;
            this.solutionId = solutionId.ToString();
		}

        internal static string GenerateJobName(string solutionName, Guid solutionId, int LCID)
        {
            return "feature-installtion" + solutionName + solutionId.ToString("D") + LCID;
        }

        public override void Execute(Guid targetInstanceId)
        {
            base.Execute(targetInstanceId);
            SPFarm farm = this.Farm;
            String[] NewFeatures = SPDUtility.GetSplitFeatures(features);
            foreach (String f in NewFeatures)
            {
                try
                {
                    farm.FeatureDefinitions.Add(f, new Guid(solutionId), Force);
                }
                catch (Exception ex) { }
            }
        }
    }
}
